﻿using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using MediaAssistant.Constants;
using MediaAssistant.Controls.ProfileSelector;
using MediaAssistant.Controls.SendFeedback;
using MediaAssistant.Controls.SplashScreen;
using MediaAssistant.Controls.StatusMessageBar;
using MediaAssistant.Controls.TopPanel;
using MediaAssistant.DAL;
using MediaAssistant.DAL.Helper;
using MediaAssistant.Data;
using MediaAssistant.Helper;
using MediaAssistant.Management;
using MefBasic;

namespace MediaAssistant
{
    public partial class App
    {
        private static bool IsAlreadyRunning()
        {
            var strLoc = Assembly.GetExecutingAssembly().Location;
            Mutex = new Mutex(true, Path.GetFileName(strLoc));
            return !Mutex.WaitOne(0, false);
        }

        public static Mutex Mutex { get; private set; }

        protected override MefBasicBootstrapper CreateBootstrapper()
        {
            return new MediaAssistantBootstrapper();
        }

        private static void HandleException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            Bootstrapper.Container.GetExportedValue<SendFeedbackPresenter>().SendException(e.Exception);
            e.Handled = true;
            Current.Shutdown();
        }
        protected override void OnBeforeRunningBootstrapper()
        {
            if (IsAlreadyRunning())
            {
                const string messageBoxText = "Media Assistant is already running";
                Logger.Instance.Write(messageBoxText);
                MessageBox.Show(messageBoxText);
                Current.Shutdown(1);
                return;
            }
            Splasher.Show();
            DispatcherUnhandledException += HandleException;
#if DEBUG
#else
            Splasher.SetMessage("Updating database");
            MediaAssistantSqliteDbEntities.UpdateDatabase();
#endif
        }

        protected override void  OnBeforeShowingMainWindow()
        {
            Splasher.SetMessage("Loading database");
            Logger.Instance.Write("Resolving MainWindowPresenter");
            var mainWindowPresenter = Bootstrapper.Container.GetExportedValue<MainWindowPresenter>();
            mainWindowPresenter.Title = "Media Assistant";

            Logger.Instance.Write("Resolving LibraryDataSource");
            var dataSource = Bootstrapper.Container.GetExportedValue<LibraryDataSource>();
            Logger.Instance.Write("Resolving InitializeDatabase");
            dataSource.InitializeDatabase();
            Splasher.SetMessage("Selecting profile");
            var profileSelectorPresenter = Bootstrapper.Container.GetExportedValue<ProfileSelectorPresenter>();
            if (profileSelectorPresenter.SelectProfile() == false)
            {
                Current.Shutdown(1);
                return;
            }
            Logger.Instance.Write("UpdateIMDBMustWatchList");
            DatabaseManager.Instance.UpdateIMDBMustWatchList();
            dataSource.UpdateTitles();
            Logger.Instance.Write("UpdateTitles");
            Splasher.SetMessage("Starting services");
            Bootstrapper.Container.GetExportedValue<BackgroundScannerManager>().Start();
            Bootstrapper.Container.GetExportedValue<StatusMessageService>().SetStatusMessage(StatusMessages.Ready);
            Bootstrapper.Container.GetExportedValue<WaitScreenService>().Hide();
        }
        protected override void OnAfterShowingMainWindow()
        {
            Logger.Instance.Write("Main Window Launched Successfully");
            Splasher.Close();
        }
        protected override void OnMainWindowClosing(CancelEventArgs e)
        {
            Bootstrapper.Container.GetExportedValue<StatusMessageBarPresenter>().SetMessage(StringTable.StopingRrunningServicesMessage);
            Bootstrapper.Container.GetExportedValue<BackgroundScannerManager>().Stop();
            Bootstrapper.Container.GetExportedValue<StatusMessageBarPresenter>().SetMessage("Unmounting Media Drive");
            var topPanelPresenter = Bootstrapper.Container.GetExportedValue<TopPanelPresenter>();
            if(topPanelPresenter.IsNightVision)
                topPanelPresenter.NightVisionWindow.Close();

        }
        protected override IMainWindow CreateMainWindow()
        {
            return new MainWindow();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            Logger.Instance.Write("OnExit");
            if(e.ApplicationExitCode==1)
            {
                return;
            }
                
            var dataSource=Bootstrapper.Container.GetExportedValue<LibraryDataSource>();
            RegistryHelper.Volume = dataSource.MusicPlayer.Volume;
            RegistryHelper.SelectedMusicDJ = dataSource.SelectedMusicDJ.Name;
            RegistryHelper.IsMuted = dataSource.MusicPlayer.IsMuted;
            base.OnExit(e);
            Logger.Instance.Write("--------------------------Exit Application------------------------");
        }
       
    }
}
